using GameFrameWork;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 游戏主控制器
/// </summary>
public class GameApp : Singleton<GameApp>
{
    [SerializeField]
    private WaveDatas m_WaveDatas;

    /// <summary>
    /// 初始阳光数量
    /// </summary>
    public int InitSunCount = 300;


    [SerializeField]
    private GameObject m_GameTips;


    public List<Plant> Plants;
    private Dictionary<int, Cell> CellsDict;
    
    // 优化：使用字典缓存植物查找，提升性能
    private Dictionary<PlantType, List<Plant>> m_PlantsByType = new Dictionary<PlantType, List<Plant>>();

    // 服务层引用
    private GameConfigService m_ConfigService;
    private EntityService m_EntityService;
    private SunSystem m_SunSystem;

    [Lablel("数字转换单位文本格式")]
    public string FormatUnitFormat = "G3";

    [Lablel("数字转换单位忽略范围（正负值）")]
    public float FormatUnitIgnoreValue = 10000;

    [Lablel("数字转换单位单位转换比例")]
    public int FormatUnitUnitScale = 10000;

    [Lablel("数字转换单位值单位组建值")]
    public string[] FormatUnitValueUnitKeys = new string[] { "万", "亿", "兆", "京" };

    [Lablel("数字转换单位字母值单位组建值")]
    public string[] FormatUnitLetterUnitKeys = new string[] { "W", "Y", "Z", "J" };

    private void Awake()
    {
        // 初始化Logger（从配置文件加载设置）
        Logger.Initialize();
        
        // 初始化服务层
        InitializeServices();
        
        // 从配置服务获取配置
        int rows = m_ConfigService.GetGridRows();
        int cols = m_ConfigService.GetGridCols();
        CellsDict = new Dictionary<int, Cell>(rows * cols);
        
        InitializePlantCache();
    }

    private void Start()
    {
        // 初始化UI管理器（确保UI层级在游戏启动时创建）
        InitializeUIManager();
        
        InitCells();
        InitializeSunSystem();
    }

    /// <summary>
    /// 初始化UI管理器。
    /// </summary>
    private void InitializeUIManager()
    {
        // 通过访问Instance来触发UIManager的初始化
        var uiManager = UIManager.Instance;
        if (uiManager != null)
        {
            // 确保UI层级已创建
            uiManager.Initialize();
            Logger.Log("GameApp", "UI Manager initialized with UI layers");
            
            // 打开CardSelectDialog界面
            int cardSelectSerialId = uiManager.OpenUIForm(UIFormId.CardSelectDialog);
            if (cardSelectSerialId > 0)
            {
                Logger.Log("GameApp", "CardSelectDialog opened successfully");
            }
            else
            {
                Logger.LogError("GameApp", "Failed to open CardSelectDialog");
            }
            
            // 打开MainCityWindow界面
            int mainCitySerialId = uiManager.OpenUIForm(UIFormId.MainCityWindow);
            if (mainCitySerialId > 0)
            {
                Logger.Log("GameApp", "MainCityWindow opened successfully");
            }
            else
            {
                Logger.LogError("GameApp", "Failed to open MainCityWindow");
            }
        }
        else
        {
            Logger.LogError("GameApp", "Failed to initialize UI Manager");
        }
    }

    /// <summary>
    /// 初始化服务层
    /// </summary>
    private void InitializeServices()
    {
        // 获取服务管理器
        var serviceManager = ServiceManager.Instance;
        
        // 获取配置服务
        m_ConfigService = serviceManager.GetService<GameConfigService>();
        if (m_ConfigService == null)
        {
            Logger.LogError("GameApp", "GameConfigService not found!");
            return;
        }
        
        // 获取实体服务
        m_EntityService = serviceManager.GetService<EntityService>();
        if (m_EntityService == null)
        {
            Logger.LogError("GameApp", "EntityService not found!");
            return;
        }
        
        // 获取阳光系统
        m_SunSystem = serviceManager.GetService<SunSystem>();
        if (m_SunSystem == null)
        {
            Logger.LogError("GameApp", "SunSystem not found!");
            return;
        }
        
        Logger.Log("GameApp", "GameApp services initialized");
    }


    private void OnEnable()
    {
        // 订阅事件
        EventHelper.Subscribe(EventType.ADD_PLANT, OnAddPlant);
    }

    private void OnAddPlant(object sender, GameEventArgs e)
    {
        if (e is AddPlantEventArgs args && args.Plant != null)
        {
            // 如果事件参数中已经有植物，说明已经添加了
            Logger.Log("GameApp", $"OnAddPlant: Plant {args.Plant.name} already added at position {args.Position}");
            return;
        }
        
        // 如果没有植物，尝试从Cell获取（这是旧的事件系统兼容）
        if (sender is Cell cell)
        {
            Logger.Log("GameApp", $"OnAddPlant called for cell at row {cell.Row}, col {cell.Column}");
            
            var plant = FindPlant(PlantType.Repeater);
            if (plant == null)
            {
                Logger.LogError("GameApp", "FindPlant returned null! Plants array may not be configured in Inspector.");
                Logger.LogError("GameApp", $"Plants array count: {(Plants != null ? Plants.Count : 0)}");
                Logger.LogError("GameApp", $"m_PlantsByType count: {m_PlantsByType.Count}");
                return;
            }
            
            Logger.Log("GameApp", $"Found plant: {plant.name}, attempting to add to cell");
            bool success = cell.AddPlant(plant);
            Logger.Log("GameApp", $"AddPlant result: {success}");
        }
    }

    private void InitCells()
    {
        // 从配置服务获取网格配置
        int rows = m_ConfigService.GetGridRows();
        int cols = m_ConfigService.GetGridCols();
        
        for (int row = 1; row <= rows; row++)
        {
            Transform parent = transform.Find($"Scene/Cells_Container/line_{row}");
            for (int col = 1; col <= cols; col++)
            {
                var obj = parent.transform.Find($"Cell_{col}");
                var comp = obj.GetComponent<Cell>();
                int key = GetKey(row, col);
                CellsDict.Add(key, comp);
            }
        }
    }

    /// <summary>
    /// 初始化植物缓存
    /// </summary>
    private void InitializePlantCache()
    {
        m_PlantsByType.Clear();
        //Logger.Log("GameApp", $"Initializing plant cache. Plants array: {(Plants != null ? Plants.Count : 0)} items");
        
        if (Plants != null)
        {
            foreach (var plant in Plants)
            {
                if (plant != null)
                {
                    var plantType = plant.GetPlantType();
                    if (!m_PlantsByType.ContainsKey(plantType))
                    {
                        m_PlantsByType[plantType] = new List<Plant>();
                    }
                    m_PlantsByType[plantType].Add(plant);
                    //Logger.Log("GameApp", $"Added plant {plant.name} of type {plantType} to cache");
                }
                else
                {
                    //Logger.LogWarning("GameApp", "Found null plant in Plants array!");
                }
            }
        }
        else
        {
            //Logger.LogError("GameApp", "Plants array is null! Please configure plants in the Inspector.");
        }
        
        //Logger.Log("GameApp", $"Plant cache initialized with {m_PlantsByType.Count} plant types");
    }

    /// <summary>
    /// 找到对应的植物
    /// </summary>
    /// <param name="plantType"></param>
    /// <returns></returns>
    private Plant FindPlant(PlantType plantType)
    {
        // 使用字典缓存，O(1)复杂度查找
        if (m_PlantsByType.TryGetValue(plantType, out var plants) && plants.Count > 0)
        {
            return plants[0]; // 返回第一个可用的植物
        }
        return null;
    }

    /// <summary>
    /// 获取唯一键
    /// </summary>
    /// <param name="row"></param>
    /// <param name="col"></param>
    /// <returns></returns>
    public int GetKey(int row, int col)
    {
        int multiplier = m_ConfigService.GetConfig("Grid.KeyMultiplier", 100);
        int key = row * multiplier + col;
        return key;
    }

    private Cell GetCell(int row, int col)
    {
        int key = GetKey(row, col);
        CellsDict.TryGetValue(key, out var cell);
        return cell;
    }

    /// <summary>
    /// 初始化阳光系统
    /// </summary>
    private void InitializeSunSystem()
    {
        if (m_SunSystem == null) 
        {
            Logger.LogError("GameApp", "SunSystem is null! Cannot initialize.");
            return;
        }
        
        Logger.Log("GameApp", "开始初始化阳光系统...");
        
        // 启用随机阳光生成
        m_SunSystem.EnableRandomSun = true;
        Logger.Log("GameApp", "✓ 随机阳光生成已启用");
        
        // 尝试加载自定义配置
        var customConfig = Resources.Load<SunSpawnConfig>("Datas/SunSpawnConfig");
        if (customConfig != null)
        {
            m_SunSystem.SetRandomSunConfig(customConfig);
            Logger.Log("GameApp", $"✓ 已加载自定义配置: {customConfig.name}");
            Logger.Log("GameApp", $"  抛物线动画: {customConfig.EnableParabolicAnimation}, 高度: {customConfig.ParabolaHeight}, 偏移: {customConfig.ParabolaHorizontalOffset}");
        }
        else
        {
            Logger.Log("GameApp", "使用默认阳光配置（将从SunSystem获取）");
            // 确保使用SunSystem的配置
            if (m_SunSystem.RandomSunConfig != null)
            {
                Logger.Log("GameApp", $"  当前配置 - 抛物线动画: {m_SunSystem.RandomSunConfig.EnableParabolicAnimation}, 高度: {m_SunSystem.RandomSunConfig.ParabolaHeight}, 偏移: {m_SunSystem.RandomSunConfig.ParabolaHorizontalOffset}");
            }
        }
        
        // 验证系统状态
        if (m_SunSystem.IsInitialized)
        {
            Logger.Log("GameApp", "✓ 阳光系统初始化完成 - 随机阳光生成已启用");
        }
        else
        {
            Logger.LogWarning("GameApp", "阳光系统可能未完全初始化");
        }

        SpawnRandomSun();
    }
    
    /// <summary>
    /// 控制随机阳光生成（供外部调用）
    /// </summary>
    public void SetRandomSunEnabled(bool enabled)
    {
        if (m_SunSystem != null)
        {
            m_SunSystem.EnableRandomSun = enabled;
            Logger.Log("GameApp", $"随机阳光生成: {(enabled ? "开启" : "关闭")}");
        }
    }
    
    /// <summary>
    /// 立即生成一个随机阳光（供外部调用）
    /// </summary>
    public void SpawnRandomSun()
    {
        if (m_SunSystem != null)
        {
            m_SunSystem.SpawnRandomSunImmediately();
            Logger.Log("GameApp", "立即生成随机阳光");
        }
        else
        {
            Logger.LogError("GameApp", "SunSystem is null! Cannot spawn random sun.");
        }
    }

    private void OnDisable()
    {
        // 取消订阅事件
        EventHelper.Unsubscribe(EventType.ADD_PLANT, OnAddPlant);
    }

}